<template>
  <div>
  <el-form size="mini">
    <el-form-item >
      <el-input :placeholder="roleName"></el-input>
    </el-form-item>
  </el-form>
  <el-tree
    :data="dataList"
    show-checkbox
    default-expand-all
    node-key="id"
    ref="tree"
    highlight-current
    :props="defaultProps">
  </el-tree>
  <el-button type="primary" size="small" @click="goRole">保存</el-button>
  <el-button  size="small" @click="cancel">取消</el-button>
</div>

</template>

<script>
import permission from '@/api/acl/permission'
// import { useUserInfoStore } from '@/stores/userInfo'
import { mapState } from 'vuex'
  export default {
    name:'roleAute',
    data(){
      return {
        id:'',
        roleName:'',
        dataList: [ ],
        defaultProps: {
          children: 'children',
          label: 'name'
        }
      }
    },
    methods:{
      // 保存
      async goRole(){
        //得到所有全选的id
        const  checkedIds = this.$refs.tree?.getCheckedKeys()
        // 得到半选id
        const halfCheckedIds = this.$refs.tree?.getHalfCheckedKeys()
        // 合并全选和半选
        let ids = checkedIds?.concat(halfCheckedIds).join(',')
        try {
           await permission.doAssign(this.id,ids)
          // console.log(first)
          this.$message.success('用户分配权限成功')
          this.$router.push('/acl/role')
           // 跳转完成后, 如果分配的是当前用户角色的权限, 刷新一下浏览器
          // const roleName = route.query.roleName
          // if (userInfoStore.userInfo.roles.includes(roleName)) {
            window.location.reload()
          // }
        } catch (error) {
          console.log('jsdk')
          this.$message.error('用户分配权限失败,请重试')
        }
        
      },
      // 取消
      cancel(){
        this.$router.push('/acl/role')
      },
      /* 
      得到所有选中的id列表
      只用得到所有选中的按钮权限数据的id
      */
      getCheckedIds  (auths,initArr)  {
        auths.forEach(item => {
          if (item.select && item.level===4) {
            initArr.push(item.id )
          } else if (item.children) {
            getCheckedIds(item.children, initArr)
          }
        })
        return initArr 
      },
      // 初始化数据
      async getroleList(){
        try {
          const {id,roleName} = this.$route.query
          this.roleName = roleName
          this.id = id
          const dataList = await permission.toAssign(id)
          this.dataList = dataList.data.children
          const checkedIds = getCheckedIds(this.dataList)
          this.tree?.setCheckedKeys(checkedIds)
        } catch (error) {
          this.$message.error('获取数据失败，请重试')
          
        }

      },
    },
    mounted() {
      this.getroleList()
    },
    computed:{
      ...mapState('user',['routes'])
      // name(){
      //   return this.$store.user.state?.name
      // }
    }
    
  }
</script>

<style scoped>
.mb-10{
  margin-bottom: 10px;
}
</style>